//
//  ViewBaseInput.swift
//  AirlineReservation
//
//  Created by Kevin on 2019/12/28.
//  Copyright © 2019 Kevin. All rights reserved.
//

import UIKit

class ViewBaseInput: UIView {
    // 文本
    private var labels = [UILabel]()
    // 输入框
    private var inputs = [TextFieldOffsetPlaceHolder]()
    // 下滑线
    private var lines = [UIView]()
    // 按钮结果回调
    public var complete: ((UserInfo) -> Void)?
    // 按钮结果回调
    public var completeDelete: ((UserInfo) -> Void)?
    // 性别选择
    private lazy var genderSelect = MarginLabel(title: NAN,color: UIColor.lightGray)
    
    // scrollView
    private var scrollView = UIScrollView()
    private var tempHeight:CGFloat = 0
    
    // 文本名称
    public var nameArrs: [String]?
    // 按钮名称
    public var titleLabel: String?
    // 是否显示按钮
    public var isShowBtn: Bool = true
    // 乘机人信息
    public var userinfo:UserInfo?
    // 是否显示删除按钮
    public var isShowDelete: Bool = false
    
    func createViews() -> Void {
        init_views()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        init_listener()
    }
    
    @objc func showKeyBoard(info:Notification) -> Void {
        let kframe = info.userInfo?[UIResponder.keyboardFrameEndUserInfoKey]
        guard let rect = kframe as? CGRect else {
            return
        }
        let kspaceh = bounds.height - rect.height
        let value = tempHeight - kspaceh
        if value > 0 {
            scrollView.setContentOffset(CGPoint(x: 0, y: value * 3), animated: true)
        }
        if value < 0  && value > -60 {
            scrollView.setContentOffset(CGPoint(x: 0, y: -value * 3), animated: true)
        }
    }
    
    @objc func hideKeyBoard(info:Notification) -> Void {
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        guard let names = nameArrs else {
            return
        }
        // 高度
        var subY:CGFloat = MARGIN
        for i in 0..<names.count {
            // 文本名称
            let label = setLabel(index: i)
            label.frame = CGRect(x: MARGIN, y: subY, width:  MARGIN * 4.8, height: MARGIN * 2)
            scrollView.addSubview(label)
            // 性别
            if let gender = label.text,gender.elementsEqual(GENDER) {
                genderSelect.frame = CGRect(x: MARGIN, y: subY - MARGIN, width: SCREEN_WIDTH, height: MARGIN * 4)
                genderSelect.contentInset = UIEdgeInsets(top: 0, left: MARGIN * 5, bottom: 0, right: 0)
                scrollView.addSubview(genderSelect)
                // 请选择文本
                let plsSelect = UILabel(title: "请选择", color: UIColor.lightGray, size: 13, align: .right)
                plsSelect.isUserInteractionEnabled = false
                let plsSelectX = frame.width - MARGIN100
                plsSelect.frame = CGRect(x: plsSelectX, y: subY - MARGIN, width: MARGIN70, height: MARGIN * 4)
                scrollView.addSubview(plsSelect)
                // 箭头
                let arrowView = UIImageView(image: UIImage(named: "arrow_7x11"))
                let arrowX = frame.width - arrowView.bounds.width - MARGIN
                let arrowY = plsSelect.frame.maxY - MARGIN * 2 - arrowView.bounds.height * 0.5
                arrowView.frame.origin = CGPoint(x: arrowX, y: arrowY)
                scrollView.addSubview(arrowView)
                // 添加点击事件
                genderSelect.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickGender)))
            }
            else {
                // 输入框
                let input = setTextField(index: i)
                input.delegate = self
                input.frame = CGRect(x: MARGIN, y: subY, width: SCREEN_WIDTH, height: MARGIN * 2)
                scrollView.addSubview(input)
            }
            // 下划线
            let line = setLine(index: i)
            line.frame = CGRect(x: MARGIN, y: MARGIN * 3 + subY , width: SCREEN_WIDTH - MARGIN * 2, height: 1)
            scrollView.addSubview(line)
            // 行间隔距离
            subY += MARGIN * 4
        }
        let orangeBtn = UIButton(title: titleLabel ?? "", name: "button_orange",radius: 5)
        if isShowBtn {
            orangeBtn.frame = CGRect(x: MARGIN, y: subY + MARGIN, width: SCREEN_WIDTH - MARGIN * 2, height: MARGIN * 3)
            scrollView.addSubview(orangeBtn)
            // 添加点击事件
            orangeBtn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        }
        // 删除按钮
        if isShowDelete {
            let deleteLabel = UILabel(title: "删除联系人", color: UIColor.orange, size: 14, align: .center)
            deleteLabel.isUserInteractionEnabled = true
            deleteLabel.frame = CGRect(x: 0, y: orangeBtn.frame.maxY + MARGIN20, width: frame.width, height: MARGIN20)
            scrollView.addSubview(deleteLabel)
            // 删除按钮 点击事件
            deleteLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickDeleteItem)))
        }
        // 赋值
        if userinfo != nil {
            inputs[0].text = userinfo?.username
            genderSelect.text = userinfo?.gender
            inputs[1].text = userinfo?.email
            inputs[3].text = userinfo?.mobile
            inputs[4].text = userinfo?.idnumber
        }
        addSubview(scrollView)
        // 设置scrollview
        scrollView.delegate = self
        scrollView.showsVerticalScrollIndicator = false
        scrollView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
        scrollView.contentSize = CGSize(width: frame.width, height: frame.height + MARGIN50)
    }
    
    
}

// MARK: 逻辑部分
extension ViewBaseInput {
    
    @objc func btnClick() -> Void {
        if let callback = complete {
            if userinfo != nil {
                userinfo?.username = inputs[0].text
                userinfo?.email = inputs[1].text
                userinfo?.mobile = inputs[3].text
                userinfo?.idnumber = inputs[4].text
                userinfo?.gender = genderSelect.text
                callback(userinfo!)
            }else {
                callback(UserInfo(dict: getTextField()))
            }
        }
    }
    
    @objc func clickDeleteItem() -> Void {
        if let callback = completeDelete,let user = userinfo {
            callback(user)
        }
    }
    
    @objc func clickGender() -> Void {
        genderSelect.text = genderSelect.text!.elementsEqual(NAN) ? NV : NAN
    }
}
// MARK: 代码不动
extension ViewBaseInput {
    
    // 获取文本框内容
    private func getTextField() -> [String:String]{
        guard let names = nameArrs else {
            return [String:String]()
        }
        var dict = [String:String]()
        for index in inputs.indices {
            let input = inputs[index].text
            switch names[index] {
            case EMAIL:
                dict[SP_EMAIL] = input
            case MOBILE:
                dict[SP_MOBILE] = input
            case USERNAME:
                dict[SP_USERNAME] = input
            case IDNUMBER:
                dict[SP_IDNUMBER] = input
            case PASSWORD_AGAIN:
                dict["passwordAgain"] = input
            case PASSWORD,INPUT_PASSWORD,NEW_PASSWORD:
                dict[SP_PASSWORD] = input
            default:
                print("")
            }
        }
        if let gender = genderSelect.text {
            dict[SP_GENDER] = gender
        }
        return dict
    }
    
    // 输入框
    private func setTextField(index:Int) -> TextFieldOffsetPlaceHolder {
        guard let names = nameArrs else {
            return TextFieldOffsetPlaceHolder()
        }
        let input = inputs[index]
        switch names[index] {
        case EMAIL:
            input.placeholder = EMAIL_TIP
            input.keyboardType = .emailAddress
        case USERNAME:
            input.keyboardType = .default
            input.placeholder = USERNAME_TIP
        case MOBILE:
            input.keyboardType = .numberPad
            input.placeholder = MOBILE_TIP
        case IDNUMBER:
            input.placeholder = IDNUMBER_TIP
            input.keyboardType = .asciiCapable
        case PASSWORD,NEW_PASSWORD:
            input.isSecureTextEntry = true
            if #available(iOS 12.0, *) {
                input.textContentType = .newPassword
            }
            if #available(iOS 10.0, *) {
                input.textContentType = .password
            }
            input.keyboardType = .asciiCapable
            input.placeholder = PASSWORD_TIP
        case PASSWORD_AGAIN:
            input.isSecureTextEntry = true
            if #available(iOS 12.0, *) {
                input.textContentType = .newPassword
            }
            if #available(iOS 10.0, *) {
                input.textContentType = .password
            }
            input.keyboardType = .asciiCapable
            input.placeholder = INPUT_PASSWORD_TIP
        default:
            input.keyboardType = .default
        }
        input.textColor = UIColor.lightGray
        input.font = UIFont.systemFont(ofSize: 13)
        input.setValue(MARGIN * 5, forKey: "paddingLeft")
        return input
    }
    
    // 文本名称
    private func setLabel(index:Int) -> UILabel {
        guard let names = nameArrs else {
            return UILabel()
        }
        let label = labels[index]
        label.text = names[index]
        label.textColor = COLOR_NICE
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }
    
    // 下划线
    private func setLine(index:Int) -> UIView {
        let line = lines[index]
        line.backgroundColor = UIColor.init(white: 237/255.0, alpha: 1)
        return line
    }
    
    // 创建views
    private func init_views() -> Void {
        guard let names = nameArrs else {
            return
        }
        (1...names.count).forEach { (i) in
            lines.append(UIView())
            labels.append(UILabel())
            inputs.append(TextFieldOffsetPlaceHolder())
        }
    }
    
    private func init_listener() {
        NotificationCenter.default.addObserver(self, selector: #selector(showKeyBoard(info:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(hideKeyBoard(info:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
}

// MARK: 代理
extension ViewBaseInput: UIScrollViewDelegate {
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollView.endEditing(true)
    }
}

extension ViewBaseInput:UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        tempHeight = textField.frame.origin.y
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        endEditing(true)
        return true
    }
}
